﻿using System.Collections.Generic;
using System.Linq;
using System;
using Systemathics.FrameWork;

namespace Systemathics.Indicators
{
    public sealed class TDDifferential : Indicator
    {
        private readonly Queue<Bar> PastBar;

        public TDDifferential(Instrument instr, Data dt, BarType bt, int value) : base(instr, dt, bt, value)
        {
            PastBar = new Queue<Bar>();
        }
        protected override void Calculate(object price)
        {
            var Bar = price as Bar;

            if (PastBar.Count < 2)
                PastBar.Enqueue(Bar.Clone() as Bar);
            else
            {
                PastBar.Enqueue(Bar.Clone() as Bar);

                var BuyingPressure = Bar.Close - Math.Min(Bar.Low, PastBar.ElementAt(1).Close);
                var PreviousBuyingPressure = PastBar.ElementAt(1).Close - Math.Min(PastBar.ElementAt(1).Low, Bar.Close);

                var SellingPressure = Math.Max(Bar.High, PastBar.ElementAt(1).Close) - Bar.Close;
                var PreviousSellingPressure = Math.Max(PastBar.ElementAt(1).High, PastBar.First().Close) - PastBar.ElementAt(1).Close;

                if (Bar.Close < PastBar.ElementAt(1).Close && PastBar.ElementAt(1).Close < PastBar.First().Close && BuyingPressure > PreviousBuyingPressure && SellingPressure < PreviousSellingPressure)
                {
                    Add(Time.Now, +1);
                    IndicatorCalculated(this);
                }
                else if (Bar.Close > PastBar.ElementAt(1).Close && PastBar.ElementAt(1).Close > PastBar.First().Close && BuyingPressure < PreviousBuyingPressure && SellingPressure > PreviousSellingPressure)
                {
                    Add(Time.Now, -1);
                    IndicatorCalculated(this);
                }

                PastBar.Dequeue();
            }
        }
    }
}